<template>
  <!--切换弹窗-->
  <van-action-sheet v-model:show="show1" title="选择预约时间段">
    <div>
      <p style="text-align: left;margin-left: 10px;font-weight: bold;">时间段</p>
      <van-radio-group>
        <van-cell-group class="time-slot-container" inset>
          <template v-for="card in registrationPoolLst" :key="card.poolListId">
            <van-cell
                class="time-slot-item"
                :class="{'disabled': card.registrationNum - card.lockNum === 0}"
                clickable
                @click="handleCardSelection(card.poolListId, card)"
            >
              <template #title>
                <p class="card-title-text time-slot">{{ card.bgnTm }}-{{card.endTm}}</p>
                <p class="card-title-text registration-num">剩余{{card.registrationNum-card.lockNum}}个号源</p>
              </template>
            </van-cell>
          </template>
        </van-cell-group>
      </van-radio-group>
    </div>
  </van-action-sheet>


  <van-loading v-if="isLoad" />
  <div v-else class="schedule-container" style="background-color: #f3f3f3">
    <div style="background-color:#ffffff;padding-top: 1px;display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;">
      <h1 style="font-size: 27px">{{ department }}</h1>
    </div>

    <div class="date-selector" style="background-color:#ffffff;">
      <div
          v-for="(day, index) in days"
          :key="index"
          :class="'day ' + { active: currentDay === index}"
          @click="selectDay(index)"
          style="padding-left: 10px;padding-right: 10px"
      >
        <p :class="day.available ? 'date exit' : 'date noExit'">{{ day.date.split('-')[2] + '号' }}</p>
        <p :class="day.available ? 'week exit' : 'week noExit'">{{ day.week }}</p>
        <p :class="{'gray': state.toString().split(',')[index] === '无号', 'green': state.toString().split(',')[index] === '有号', 'red': state.toString().split(',')[index] === '满号'}">
          {{ state.toString().split(',')[index] }}</p>
      </div>
    </div>

    <div class="doctor-schedule" v-if="currentDay !== null">
      <h2>{{ days[currentDay].date }} {{ days[currentDay].week }}</h2>
      <van-cell-group v-if="show">
        <van-cell v-for="(item, index) in arrangementCard" :key="item.arrangementId" center clickable size="large">
          <template #icon>
            <img
                :src="require('@/assets/images/'+item.photo)"
                alt="医生图片"
                style="max-width: 60px; max-height: 60px;border-radius: 50%;margin-right: 20px"
            />
          </template>
          <template #title>
            <div class="title-text"
                 style="display: flex; justify-content: flex-start; align-items: center; margin-left: 30px; flex-direction: row; margin-bottom: 1px;">
              <h5 style="font-size: 16px;margin-left: -30px; ">{{ item.ename }}</h5>
              <span class="doctor-title">{{ item.etitle }}</span>
            </div>
          </template>

          <template #label>
            <div class="label-container" style="margin-top: -10px;">
              <a href="#" style="position: absolute; top: 0; right: 0; margin: 10px; color: red;">全部排班</a>
              <p class="label-text" style="color: black;">
                <span class="label-text-block"
                      style="color: gray;display: block; margin-bottom: 5px;text-align: left;">{{ item.post }}</span>

                <span :class="{ available: !isAvailable(item), unavailable: isAvailable(item) }">
                  {{ isAvailable(item) ? '无号' : '有号' }}
                </span>

                - 就诊时间：<span style="color: black;">{{ item.arrangementDt }} {{
                  days[currentDay].week
                }} {{ item.workTime}}</span>
                <br>
                <span style="font-size: 13px;margin-right: 27px;text-align: left; ">总号:{{
                    item.registrationNum
                  }}</span>
                <span style="font-size: 13px;margin-right: 27px;">剩余:{{
                    item.registrationNum - item.lockNum
                  }}</span>
                <span style="font-size: 13px;text-align: right;" class="unavailable">价格:¥ {{
                    item.registrationPrice
                  }}</span>
              </p>
              <div class="button-wrapper">
                <van-button type="primary" size="small" @click="appoint(index)">挂号</van-button>
              </div>
            </div>
          </template>
        </van-cell>

      </van-cell-group>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {ArrangementService, DepartService, RegistrationPoolService} from "@/api/api";
import router from "@/router";

const show1 = ref(false);
const show = ref(false);
let department = '内科';
let departmentId = '1';
const currentDay = ref(null);
const isLoad = ref(true);
let state = ref([
  {
    state: '-1'
  }
]);


let arrangementCard = ref([
  {
    arrangementId: '-1',
    business:'-1',
    ename: '-1',
    eType: '-1',
    arrangementDt: '-1',
    photo: 'doctor.png',
    addNum: '-1',
    lockNum: '-1',
    etitle: '-1',
    registrationNum: '-1',
    registrationPrice: '-1',
    post: '-1',
    workTime:'-1'
  }
]);

let arrangement = ref([
  {
    arrangementId: '-1',
    business:'-1',
    ename: '-1',
    eType: '-1',
    arrangementDt: '-1',
    photo: 'doctor.png',
    lockNum: '-1',
    etitle: '-1',
    registrationNum: '-1',
    registrationPrice: '-1',
    post: '-1',
    workTime:'-1'
  }
]);

// eslint-disable-next-line no-unused-vars
let registrationPoolLst= ref([
  {
    poolListId:'-1',
    bgnTm : '-1',
    endTm :'-1',
    registrationNum : '-1',
    lockNum:'-1',
    registrationPrice:'-1'
  }
]);

//开始就启动计算出后七天的排班号源状态

onMounted(async () => {
  console.log(history.state.departId);
  // DepartService.getDepartName(history.state.departId);
  // console.log(DepartService.getDepartName(history.state.departId));
  departmentId = history.state.departId;
  const response = await DepartService.getDepartName(history.state.departId);
  department = response.data;
  // departmentId = history.state.departId;
  await loadData(); // 在页面加载完成后调用加载数据的方法
});

async function loadData() {
  try {
    const currentDate = new Date();
    const currentDay = currentDate.getDate();
    const currentMonth = currentDate.getMonth() + 1;
    const currentYear = currentDate.getFullYear();
    const response = await ArrangementService.stateByDt(departmentId, `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`);
    // 获取响应数据
    state.value = response.data; // 将响应数据存储在 patientCard 变量中
    show.value = true;
    await selectDay(0);
    isLoad.value = false;
  } catch (error) {
    console.error(error); // 处理错误
  }
}

//得出该星期的日期和星期
const getWeekDays = () => {
  const currentDate = new Date();
  const currentDay = currentDate.getDate();
  const currentMonth = currentDate.getMonth() + 1;
  const currentYear = currentDate.getFullYear();
  const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

  const currentWeekday = daysOfWeek[currentDate.getDay()];
  const futureDays = [];
  console.log(state.value); // 输出结果
  futureDays.push({
        date: `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}-${currentDay < 10 ? '0' + currentDay : currentDay}`,
        week: currentWeekday,
        available: true,
      }
  ); // 添加今天的日期和星期
  for (let i = 0; i < 6; i++) {
    const nextDate = new Date(currentDate);
    nextDate.setDate(currentDay + i + 1);
    const nextDay = nextDate.getDate();
    const nextMonth = nextDate.getMonth() + 1;
    const nextYear = nextDate.getFullYear();
    const nextWeekday = daysOfWeek[nextDate.getDay()];
    futureDays.push({
          date: `${nextYear}-${nextMonth < 10 ? '0' + nextMonth : nextMonth}-${nextDay < 10 ? '0' + nextDay : nextDay}`,
          week: nextWeekday,
          available: true
        }
    );
  }

  return futureDays;
};

const days = getWeekDays();


//计算具体排班是否有号
const isAvailable = (item) => {
  return item.addNum + item.registrationNum === item.lockNum;
};

//选择具体某个日期的排班
const selectDay = async (index) => {
  try {
    if (days[index].available) {
      currentDay.value = index;
    }
    const date = days[index].date;
    const response1 = await ArrangementService.findAllByDepartmentIdAndArrangementDt(departmentId, date);
    arrangementCard.value = response1.data;
    // 将响应数据存储在 patientCard 变量中
    show.value = true;
  } catch (error) {
    console.error(error); // 处理错误
  }
};

const appoint =  async (index) => {
  try {
    arrangement.value = arrangementCard.value[index];
    const response = await RegistrationPoolService.findVoByArrangementId(arrangement.value.arrangementId);
    registrationPoolLst.value = response.data;
    show1.value = true;
  } catch (error) {
    console.error(error); // 处理错误
  }
};

const handleCardSelection = async (planLstId, registrationPoolLst) => {
  show1.value = false;
  try {
    const data = {
      poolListId: planLstId,
    };

    await router.push({
      path: '/ConfirmAppointment',
      state: data
    });
  } catch (error) {
    console.error(error);
  }
  console.log(registrationPoolLst);
};

</script>

<style>

.date-selector {
  display: flex;
  justify-content: space-between;
}


.gray {
  color: gray;
}

.green {
  color: green;
}

.red {
  color: red;
}


.label-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-wrapper {
  font-size: 12px;
}

.button-wrapper button {
  font-size: inherit;
}


.date-selector {
  display: flex;
  overflow-x: auto;
}

.title-text {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

h5 {
  font-size: 14px;
  margin: 0;
}

.doctor-title {
  font-size: 12px;
  color: brown;
  font-weight: bold;
  margin-left: 15px;
  display: inline-block;
  background: linear-gradient(to bottom, #E0F3FF, #B3E0FF); /* 添加渐变背景色 */
  padding: 2px 5px; /* 调整背景填充的边距 */
  border-radius: 4px; /* 添加边框圆角 */
}

.label-text {
  margin-bottom: 2px;
  font-size: 12px;
}

.available,
.unavailable {
  font-size: 12px;
}

.doctor-schedule {
  margin-top: 20px;
}

h2 {
  font-size: 18px;
  margin: 0 0 10px;
}

h3 {
  font-size: 16px;
  margin: 0 0 5px;
}

.available {
  color: #6abf47;
}

.unavailable {
  color: #f56c6c;
}
.time-slot-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.time-slot-item {
  width: 48%;
  margin-bottom: 10px;
  border-radius: 5px;
  padding: 10px;
  background: linear-gradient(to bottom, #E0F3FF, #B3E0FF); /* 添加渐变背景色 */
}

.time-slot {
  font-size: 16px;
  margin-bottom: 5px;
}

.registration-num {
  font-size: 14px;
}


.card-title-text {
  line-height: 0.4;
}

.time-slot-item.disabled {
  opacity: 0.4; /* 或者其他灰色值 */
  cursor: not-allowed;
  pointer-events: none;
}
</style>
